package com.ruoyi.customer.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.customer.domain.CsContract;
import com.ruoyi.customer.domain.CsCustomer;
import com.ruoyi.customer.domain.CsSea;
import com.ruoyi.customer.mapper.CsContractMapper;
import com.ruoyi.customer.service.ICsContractService;
import com.ruoyi.customer.service.ICsCustomerService;
import com.ruoyi.customer.service.ICsSeaService;
import com.ruoyi.system.service.ISysRoleService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.util.Date;
import java.util.List;

/**
 * 合同管理Service业务层处理
 *
 * @author 李守壮
 * @date 2023-03-18
 */
@Service
public class CsContractServiceImpl implements ICsContractService {

    private static final Logger log = LoggerFactory.getLogger(CsContractServiceImpl.class);

    @Autowired
    protected Validator validator;

    @Autowired
    private CsContractMapper csContractMapper;

    @Autowired
    private ICsCustomerService customerService;

    @Autowired
    private ICsSeaService seaService;

    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 查询合同管理
     *
     * @param id 合同管理主键
     * @return 合同管理
     */
    @Override
    public CsContract selectCsContractById(Long id) {
        return csContractMapper.selectCsContractById(id);
    }

    /**
     * 查询合同管理列表
     *
     * @param csContract 合同管理
     * @return 合同管理
     */
    @Override
    public List<CsContract> selectCsContractList(CsContract csContract) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        //获取用户角色
        List<Long> roleList = sysRoleService.selectRoleListByUserId(userId);
        if (roleList.size() == 1 && roleList.get(0) == 5) { //一个角色且是员工staff，那么就只能看自己创建的合同
            csContract.setCreateBy(SecurityUtils.getLoginUserIdTypeString());
        }
        return csContractMapper.selectCsContractList(csContract);
    }


    /**
     * 新增合同管理
     *
     * @param csContract 合同管理
     * @return 结果
     */
    @Override
    public int insertCsContract(CsContract csContract) {
        try {
            // 新建合同时查询客户信息，没有则新增
            CsCustomer csCustomer = customerService.getByPhone(csContract.getMobile());
            if (ObjectUtils.isEmpty(csCustomer)) {
                CsCustomer insertCustomer = new CsCustomer();
                String contractCode = "ZJ" + DateUtils.getTimestampNow();
                insertCustomer.setCompanyContractCode(contractCode);
                insertCustomer.setTelephone(csContract.getMobile());
                insertCustomer.setCompanyCode(csContract.getCompanyCode());
                insertCustomer.setCompanyName(csContract.getCompanyName());
                insertCustomer.setCompanyStatus(1);
                insertCustomer.setCompanyUserName(csContract.getCompanyUserName());
                insertCustomer.setCompanyTitle(csContract.getCompanyTitle());
                insertCustomer.setSalesId(SecurityUtils.getUserId());
                insertCustomer.setSalesEmail(SecurityUtils.getLoginUser().getUser().getEmail());
                insertCustomer.setSalesMobile(SecurityUtils.getLoginUser().getUser().getPhonenumber());
                insertCustomer.setSalesName(SecurityUtils.getLoginUsername()); // 销售名称为 用户名
                insertCustomer.setCreateBy(SecurityUtils.getLoginUserIdTypeString());//创建人为当前登录ID
                customerService.insertCsCustomer(insertCustomer);

                //将客户公海中的数据置为合同阶段
                String companyId = csContract.getCompanyId();
                if (StringUtils.isNotEmpty(companyId)) {
                    try {
                        long id = Long.parseLong(companyId);
                        CsSea csSea = seaService.selectCsSeaById(id);
                        if (ObjectUtils.isNotEmpty(csSea)) {
                            csSea.setFollowStatus("5"); //修改客户跟进状态为5，而非置为删除状态，已用作后续数据流转
                            csSea.setUpdateBy(SecurityUtils.getLoginUserIdTypeString());
                            csSea.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
                            seaService.updateCsSea(csSea);
                        }
                    } catch (NumberFormatException exception) {
                        log.error(exception.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        //处理合同新增逻辑
        String contractCode = "ZJCT" + DateUtils.getTimestampNow();
        csContract.setContractCode(contractCode);
        csContract.setCreateBy(SecurityUtils.getLoginUserIdTypeString());
        return csContractMapper.insertCsContract(csContract);
    }

    /**
     * 修改合同管理
     *
     * @param csContract 合同管理
     * @return 结果
     */
    @Override
    public int updateCsContract(CsContract csContract) {
        csContract.setUpdateTime(DateUtils.getNowDate());
        csContract.setUpdateBy(SecurityUtils.getLoginUserIdTypeString());
        return csContractMapper.updateCsContract(csContract);
    }

    /**
     * 批量删除合同管理
     *
     * @param ids 需要删除的合同管理主键
     * @return 结果
     */
    @Override
    public int deleteCsContractByIds(Long[] ids) {
        for (Long id : ids) {
            CsContract obj = new CsContract();
            obj.setId(id);
            obj.setDelFlag("2");
            obj.setUpdateTime(DateUtils.getNowDate());
            obj.setUpdateBy(SecurityUtils.getLoginUserIdTypeString());
            csContractMapper.updateCsContract(obj);
        }
        return 1;
    }

    /**
     * 删除合同管理信息
     *
     * @param id 合同管理主键
     * @return 结果
     */
    @Override
    public int deleteCsContractById(Long id) {
        return csContractMapper.deleteCsContractById(id);
    }


    /**
     * 导入数据
     */
    @Override
    public String importData(List<CsContract> list, Boolean isUpdateSupport, String operName) {
        if (ObjectUtils.isEmpty(list)) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (CsContract record : list) {
            try {
                // 验证是否存在这个数据
                // 验证是否存在客户名称
                String companyName =record.getCompanyName();
                Date contractStartDate = record.getContractStartDate();
                Date contractEndDate = record.getContractEndDate();
                if (companyName == null || companyName.equals("") ||contractStartDate == null || contractStartDate.equals("") ||contractEndDate == null || contractEndDate.equals("") ){
                    String msg = "<br/> 没有客户名称会报错的， 导入失败：";
                    failureMsg.append(msg);
                }
                CsContract u = getByCompanyNameAndTime(companyName,contractStartDate,contractEndDate);
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, record);
                    this.fastInsertCsContract(record);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、客户名称： " + record.getId() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, record);
                    record.setUpdateBy(operName);
                    this.updateCsContract(record);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、客户名称： " + record.getId() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、客户名称： " + record.getId() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、客户名称： " + record.getId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public String disableContract() {
        List<CsContract> csContracts = csContractMapper.selectTimeoutCsContract();
        int updated = 0;
        for (CsContract csContract : csContracts) {
            csContract.setStatus("1");
            int success = csContractMapper.updateCsContract(csContract);
            updated += success;
        }
        return "有" + updated + "条合同到期";
    }


    /**
     * 用客户名称找，因为中国公司全称不可以雷同
     */
    public CsContract getByCompanyNameAndTime(String companyName, Date contractStartDate,Date contractEndDate) {
        CsContract obj = new CsContract();
        obj.setCompanyName(companyName);
        obj.setContractStartDate(contractStartDate);
        obj.setContractEndDate(contractEndDate);
        List<CsContract> csContracts = csContractMapper.selectCsContractList(obj);
        if (ObjectUtils.isNotEmpty(csContracts)) {
            return csContracts.get(0);
        }
        return null;
    }



    /**
     * 新增
     * 快速插入
     * @return 结果
     */
    public int fastInsertCsContract(CsContract csContract) {
        String code = "ZJCS"+DateUtils.getTimestampNow();
        csContract.setCompanyCode(code);
        csContract.setCreateBy(SecurityUtils.getLoginUserIdTypeString());
        return csContractMapper.insertCsContract(csContract);
    }



}
